class CourseController < ApplicationController
  before_filter :login_required, :only => [ :show, :enroll, :add_event, :list_own ]
  before_filter :admin_required, :only => [ :create, :new, :destroy ]
  before_filter :instructor_required, :only => [ :edit, :update ]

  # Mismo que list
  def index
    list
    render :action => 'list'
  end

  # Enrola al usuario actual al curso con id ":id".
  # Le muestra una interfaz en la que le pregunta si se quiere enrolar al curso,
  # si selecciona que sí hace un post a este mismo action. Si no, se regresa a
  # la lista.
  # TBDecided: Se podría usar AJAX para esto. ¿Queremos hacer eso?
  def enroll
    if params[:id].nil?
      redirect_to :action => 'index'
      return
    end


    @course = Course.find(params[:id])

    if @course.name == "Eventos Globales" and self.is_student?
      logger.debug(@course.to_yaml)
      flash[:error]="No te puedes unir a este curso."
      redirect_to :action => 'index'
    end

    user = self.current_user
    if user.courses.include?(@course)
      flash[:error] = "Ya eres parte de este curso!"
      redirect_to :action => 'index'
      return
    end

    return if request.get?

    user.courses << @course

    flash[:notice] = "Exitosamente a&ntilde;adido al curso #{@course.name}"
    redirect_to :action => 'index'
  rescue ActiveRecord::RecordNotFound
    flash[:error] = "No puedo encontrar curso con id #{params[:id]}"
    redirect_to :action => 'index'
  rescue Exception => e
    flash[:error] = "Error: "+e.message + "<br>Backtrace: "+e.backtrace.join("<br>")
    redirect_to :action => 'index'
  end

  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],
         :redirect_to => { :action => :list }

  # Lista los cursos disponibles. Muestra por cada uno:
  #  Nombre del curso
  #  Descripcion (truncada a 45 caracteres)
  #  Fecha de fin de curso.
  def list
    @title = "Cursos"
    @course_pages, @all_courses = paginate :all_courses, :singular_name => 'course', :per_page => 13
  end

  # Entra al curso dado, segun el rol del usuario actual es lo que muestra.
  # TODO: Hacer vistas!
  def show
    @course = Course.find(params[:id])
    logger.debug(@course.to_yaml)
    @in_there = self.current_user.courses.include?(@course)

    # El curso no ha caducado aún...
    if @course.end_date.nil? or Time.now < @course.end_date or @in_there or self.is_admin?
      redirect_to(:action => 'enroll', :id => @course) and return if not @in_there and not self.is_admin?

      now = Time.now
      @events = @course.events
      @events = @events.select { |e| e.expire_date < now } if self.is_student?
      @assignments = @course.assignments
      @users = @course.users
      if self.is_instructor? or self.is_admin?
        tmp = @course.assignments.map { |a|
          a.assignment_answers.map { |n|
            [ n.user, n.grade * a.weight ]
          }
        }
        @average = {}
        tmp.each { |t|
          t.each { |a|
            if @average[ a[0] ]
              @average[ a[0] ] += a[1]
            else
              @average[ a[0] ] = a[1]
            end
          }
        }
      else
        @answered = {}
        @assignments.each { |a|
          for a in a.assignment_answers
            if a.user = current_user
              answered[a] = true
              break
            end
          end
        }
      end
      render(:file => 'course/show_instructor', :use_full_path => true, :layout => true)  if self.is_instructor? or self.is_admin?
      render(:file => 'course/show_student', :use_full_path => true, :layout => true) if self.is_student?
    else
      flash[:notice] = "El curso ya termin&oacute;."
      redirect_to(:controller => 'account', :action => 'index')
    end
  rescue ActiveRecord::RecordNotFound
    flash[:error] = "No puedo encontrar curso con id #{params[:id]}"
    redirect_to :action => 'index'
  end

  # Crea un nuevo curso
  def new
    @course = Course.new
  end

  # Hace la accion de crear un nuevo curso.
  def create
    redirect_to(:action => 'new') and return unless request.post?
    @course = Course.new(params[:course])
    @course.creator = self.current_user
    if @course.save
      flash[:notice] = 'Curso creado existosamente.'
      redirect_to :action => 'list'
    else
      render :action => 'new'
    end
  end

  # Muestra lo necesario para editar a un curso
  def edit
    @course = Course.find(params[:id])
  end

  # Hace la edición del curso en si.
  def update
    @course = Course.find(params[:id])
    if @course.update_attributes(params[:course])
      flash[:notice] = 'Course was successfully updated.'
      redirect_to :action => 'show', :id => @course
    else
      render :action => 'edit'
    end
  end

  # Borra un curso.
  def destroy
    curso = Course.find(params[:id])
    curso.destroy
    redirect_to :action => 'list'
  rescue
    flash[:error] = "Error borrando el curso con id = #{params[:id]}".
    redirect_to :action => 'list'
  end

  # Muestra una lista de tus propios cursos
  def list_own
    @course_pages = Paginator.new self, @side_courses.size , 13, params[:page]
    @all_courses = @side_courses[@course_pages.current.offset..@course_pages.current.last_item]
    render :action => 'list'
  end
end
